﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
namespace CTOOLS
{
    public class EmailWebClass
   { 
        private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        private MailMessage me;//主要处理发送邮件的内容，例：收发件人地址、标题、主体、图片
        private SmtpClient sc;   //主要处理用smtp发送邮件的配置信息，例：发送邮件服务器地址、发送端口号、验证方式
        private int mSenderPort;                         //发送邮件所用的端口号（htmp协议默认为25）
        private string mSenderServerHost;          //发件箱的邮件服务器地址（IP形式或字符串形式均可）
        private string mSenderUserName;           //发件箱的用户名（即@符号前面的字符串，例如：hello@163.com，用户名为：hello）
        private string mSenderPassword;             //发件箱的密码
        private bool mEnableSsl;                         //是否对邮件内容进行socket层加密传输
        private bool mEnablePwdAuthentication;  //是否对发件人邮箱进行密码验证

        ///<summary>
        /// <strong><span style="color:#ff0000;">构造函数</span></strong>
        ///</summary>
        ///<param name="server">发件箱的邮件服务器地址</param>
        ///<param name="toMail">收件人地址（可以是多个收件人，程序中是以“;"进行区分的）</param>
        ///<param name="CCMail">抄送人地址</param>
        ///<param name="BCCMail">秘送人地址</param>
        ///<param name="fromMail">发件人地址</param>
        ///<param name="subject">邮件标题</param>
        ///<param name="emailBody">邮件内容（可以以html格式进行设计）</param>
        ///<param name="username">发件箱的用户名（即@符号前面的字符串，例如：hello@163.com，用户名为：hello）</param>
        ///<param name="password">发件人邮箱密码</param>
        ///<param name="port">发送邮件所用的端口号（htmp协议默认为25）</param>
        ///<param name="sslEnable">true表示对邮件内容进行socket层加密传输，false表示不加密</param>
        ///<param name="pwdCheckEnable">true表示对发件人邮箱进行密码验证，false表示不对发件人邮箱进行密码验证</param>
        public EmailNetClass(string server, string toMailAddress, string CCMail, string BCCMail, string fromMailAddress, string emailTitle, string emailBody, string username, string password, string port, bool sslEnable, bool pwdCheckEnable)
        {
            try
            {
                me = new MailMessage();
                string[] topath = toMailAddress.Split(';'); //以什么符号分隔可以自定义
                string[] ccpath = CCMail.Split(';'); //以什么符号分隔可以自定义
                string[] bccpath = BCCMail.Split(';'); //以什么符号分隔可以自定义
                foreach (string top in topath)
                {
                    me.To.Add(top);
                }
                foreach (string ccp in ccpath)
                {
                    me.CC.Add(ccp);
                }
                foreach (string bcp in bccpath)
                {
                    me.Bcc.Add(bcp);
                }
                me.From = new MailAddress(fromMailAddress);
                me.Subject = emailTitle;
                me.Body = emailBody;
                me.IsBodyHtml = true;
                me.BodyEncoding = System.Text.Encoding.UTF8;
                me.Priority = MailPriority.Normal;
                this.mSenderServerHost = server;
                this.mSenderUserName = username;
                this.mSenderPassword = password;
                this.mSenderPort = Convert.ToInt32(port);
                this.mEnableSsl = sslEnable;
                this.mEnablePwdAuthentication = pwdCheckEnable;
            }
            catch (Exception ex)
            {
                log.Error("设置邮件参数失败!", ex);
            }
        }

        ///<summary>
        /// <strong><span style="color:#ff0000;">添加附件</span></strong>
        ///</summary>
        ///<param name="attachmentsPath">附件的路径集合，以分号分隔</param>
        public bool AddAttachments(string attachmentsPath)
        {
            bool bReturn = false;
            try
            {
                if (!string.IsNullOrEmpty(attachmentsPath))
                {
                    string[] path = attachmentsPath.Split(';'); //以什么符号分隔可以自定义
                    Attachment data;
                    ContentDisposition disposition;
                    for (int i = 0; i < path.Length; i++)
                    {
                        data = new Attachment(path[i], MediaTypeNames.Application.Octet);
                        disposition = data.ContentDisposition;
                        disposition.CreationDate = File.GetCreationTime(path[i]);
                        disposition.ModificationDate = File.GetLastWriteTime(path[i]);
                        disposition.ReadDate = File.GetLastAccessTime(path[i]);
                        me.Attachments.Add(data);
                    }
                }

                bReturn = true;
            }
            catch (Exception ex)
            {
                log.Error("设置邮件附件失败!", ex);
            }
            return bReturn;
        }

        ///<summary>
        /// <strong><span style="color:#ff0000;">邮件的发送</span></strong>
        ///</summary>
        public bool Send()
        {
            bool bReturn = false;
            try
            {
                if (me != null)
                {
                    sc = new SmtpClient();
                    //mSmtpClient.Host = "smtp." + mMailMessage.From.Host;
                    sc.Host = this.mSenderServerHost;
                    sc.Port = this.mSenderPort;
                    sc.UseDefaultCredentials = false;
                    sc.EnableSsl = this.mEnableSsl;
                    if (this.mEnablePwdAuthentication)
                    {
                        System.Net.NetworkCredential nc = new System.Net.NetworkCredential(this.mSenderUserName, this.mSenderPassword);
                        //mSmtpClient.Credentials = new System.Net.NetworkCredential(this.mSenderUsername, this.mSenderPassword);
                        //NTLM: Secure Password Authentication in Microsoft Outlook Express
                        sc.Credentials = nc.GetCredential(sc.Host, sc.Port, "NTLM");
                    }
                    else
                    {
                        sc.Credentials = new System.Net.NetworkCredential(this.mSenderUserName, this.mSenderPassword);
                    }

                    sc.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                    sc.Send(me);
                    bReturn = true;
                }

            }
            catch (System.Net.Mail.SmtpException ex)
            {
                log.Error("邮件发送失败!", ex);
            }
            return bReturn;
        }

    }
}

